package com.ruoyi.web.controller.teaching;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.teaching.domain.PlatformEEvent;
import com.ruoyi.teaching.service.PlatformEEventService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.Valid;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 王旭
 * @since 2025-03-03
 */
@RestController
@RequestMapping("/platform/event")
@Api(tags = "platform-赛事管理")
@Validated
public class PlatformEEventController {
    @Autowired
    private PlatformEEventService platformEEventService;

    // static {
    //     try {
    //         // 创建信任所有证书的TrustManager
    //         TrustManager[] trustAllCerts = new TrustManager[]{
    //                 new X509TrustManager() {
    //                     public X509Certificate[] getAcceptedIssuers() {
    //                         return null;
    //                     }
    //
    //                     public void checkClientTrusted(X509Certificate[] certs, String authType) {
    //                     }
    //
    //                     public void checkServerTrusted(X509Certificate[] certs, String authType) {
    //                     }
    //                 }
    //         };
    //         // 初始化SSLContext
    //         SSLContext sc = SSLContext.getInstance("SSL");
    //         sc.init(null, trustAllCerts, new java.security.SecureRandom());
    //         // 设置默认的SSLSocketFactory
    //         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    // }

    /**
     * 发布赛事
     */
    @PostMapping("/addEvent")
    @ApiOperation(value = "发布赛事", notes = "发布赛事")
    @Log(title = "【发布赛事】", businessType = BusinessType.INSERT)
    public AjaxResult addEvent(@RequestBody @Valid PlatformEEvent platformEEvent) {
        // 校验结束时间不能早于开始时间
        if (platformEEvent.getApplyStartTime() != null && platformEEvent.getApplyEndTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startTime = sdf.parse(platformEEvent.getApplyStartTime());
                Date endTime = sdf.parse(platformEEvent.getApplyEndTime());

                if (!startTime.before(endTime)) {
                    return AjaxResult.error("报名结束时间必须晚于开始时间");
                }
            } catch (ParseException e) {
                return AjaxResult.error("时间格式不正确，正确格式为yyyy-MM-dd HH:mm:ss");
            }
        }

        Integer eventLevel = platformEEvent.getEventLevel();
        if (eventLevel != null && eventLevel != 0 && eventLevel != 1 && eventLevel != 2) {
            return AjaxResult.error("赛事等级不合法");
        } else if (eventLevel != null && (eventLevel == 1 || eventLevel == 2)) {
            String eventApplyUrl = platformEEvent.getEventApplyUrl();
            if (StringUtils.isBlank(eventApplyUrl)) {
                return AjaxResult.error("报名链接不能为空");
            } else if (!eventApplyUrl.startsWith("http://") && !eventApplyUrl.startsWith("https://")) {
                return AjaxResult.error("报名链接必须以http://或https://开头");
            }
            // else if (!isUrlAccessible(eventApplyUrl)) {
            //     return AjaxResult.error("报名链接不可访问");
            // }
        }

        return platformEEventService.addEvent(platformEEvent);
    }

    // /**
    //  * 校验URL是否可访问
    //  */
    // private boolean isUrlAccessible(String urlString) {
    //     HttpURLConnection connection = null;
    //     try {
    //         URL url = new URL(urlString);
    //         connection = (HttpURLConnection) url.openConnection();
    //         connection.setConnectTimeout(5000);
    //         connection.setReadTimeout(5000);
    //         connection.setRequestMethod("GET");
    //         connection.setInstanceFollowRedirects(true); // 跟随重定向
    //         connection.connect();
    //         int responseCode = connection.getResponseCode();
    //         return responseCode >= 200 && responseCode < 400;
    //     } catch (IOException e) {
    //         return false;
    //     } finally {
    //         if (connection != null) {
    //             connection.disconnect();
    //         }
    //     }
    // }

    /**
     * 删除赛事
     */
    @DeleteMapping("/deleteEvent")
    @ApiOperation(value = "删除赛事", notes = "删除赛事")
    @Log(title = "【删除赛事】", businessType = BusinessType.DELETE)
    public AjaxResult deleteEvent(Long[] ids) {
        return platformEEventService.deleteEvent(ids);
    }

    /**
     * 后台查询赛事报名
     */
    @GetMapping("/queryEventSignUp")
    @ApiOperation(value = "后台查询赛事报名", notes = "后台查询赛事报名")
    public AjaxResult queryEventSignUp(Integer pageNum, Integer PageSize, String eventName, Integer eventStatus, Integer eventLevel, Integer professionalCategoryId) {
        return platformEEventService.queryEventSignUp(pageNum, PageSize, eventName, eventStatus, eventLevel, professionalCategoryId);
    }

    /**
     * 增加浏览量
     */
    @PutMapping("/addBrowseCount")
    @ApiOperation(value = "增加浏览量", notes = "增加浏览量")
    public AjaxResult addBrowseCount(Long id) {
        return platformEEventService.addBrowseCount(id);
    }

    /**
     * 前台查询赛事
     */
    @GetMapping("/queryEventList")
    @ApiOperation(value = "前台查询赛事", notes = "前台查询赛事")
    public AjaxResult queryEventList(Integer pageNum, Integer pageSize, String eventName, Integer eventStatus, Integer eventLevel, Integer professionalCategoryId, Integer professionalId, Integer sort) {
        return platformEEventService.queryEventList(pageNum, pageSize, eventName, eventStatus, eventLevel, professionalCategoryId, professionalId, sort);
    }

    /**
     * 根据id获取详情信息
     */
    @GetMapping("/getById/{id}")
    @ApiOperation(value = "根据id获取详情信息", notes = "根据id获取详情信息")
    public AjaxResult getEventInfoById(@PathVariable("id") Long id) {
        return platformEEventService.getEventInfoById(id);
    }

    /**
     * 查询地区
     */
    @GetMapping("/selectArea")
    @ApiOperation(value = "查询地区", notes = "查询地区")
    public AjaxResult selectArea() {
        return platformEEventService.selectArea();
    }

}

